(function () {

	'use strict';

	angular
		.module('app')
		.factory('AddressEditModel', AddressEditModel);

	AddressEditModel.$inject = ['$http', '$q', '$timeout', '$rootScope', 'CacheFactory', 'API', 'ENUM', 'AppAuthenticationService'];

	function AddressEditModel($http, $q, $timeout, $rootScope, CacheFactory, API, ENUM, AppAuthenticationService) {

		var service = {};
		service.isLoaded = false;
		service.isLoading = false;
		service.address = null;
		service.regions = null;
		service.save = function (addressID, receiver_name, mobile, region_id, full_address) {
            if (!AppAuthenticationService.getToken())
                return;

            return API.consignee.addAddress({
                address_id: addressID,
                receiver_name: receiver_name,
                mobile: mobile,
                district: region_id,
                full_address: full_address
            }).then(function (res) {
                return res ? true : false;
            });
        };

        service.clear = function() {
            this.address = null;
		};

		service.reload = _reload;
		service.reloadIfNeeded = _reloadIfNeeded;
		return service;

		function _reload() {
			if (!AppAuthenticationService.getToken())
				return;

			if (this.isLoading)
				return;

			this.isLoading = true;

			var _this = this;
			return API.region.getRegion({}).then(function (res) {
				if (res && res.length) {
					_this.isLoading = false;
					_this.isLoaded = true;
					_this.regions = res;
				} else {
                    service.toast('没有可选地址');
				}
				return res ? true : false;
			});
		}

		function _reloadIfNeeded() {
			if (!AppAuthenticationService.getToken())
				return;

			if (!this.isLoaded) {
				return this.reload();
			} else {
				var deferred = $q.defer();
				$timeout(function () {
					deferred.resolve(true);
				}, 1);
				return deferred.promise;
			}
		}

	}

})();